<?php

namespace app\api\middleware;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use app\common\Error;
use app\common\Common;


class CheckToken
{
    public function handle($request, \Closure $next)
    {
        $url = Request::controller() . '/' . Request::action();

        $requestUrl = strtolower($url);

        $notAuthRequestUrl = [

            'index/index',
            'weixin/index',
            'weixin/getminigamecpslist',
            'weixin/wxgamelist',

        ];

        if (!in_array($requestUrl, $notAuthRequestUrl)) {
            $header = Request::header();
            $token = !empty($header['token']) ? $header['token'] : '';
            if (!$token) {
                return Common::fail(Error::PLEASE_LOGIN_FIRST, Error::NOT_LOGGED_CODE);
            }

            $redis = Cache::store('redis')->handler();
            $redis->select(8);
            $uid = $redis->get($token);

            if (empty($uid)) {
                return Common::fail(Error::PLEASE_LOGIN_FIRST, Error::NOT_LOGGED_CODE);
            }

            $key = config('redis_key.api.user_login') . $uid;

            $userInfo = $redis->get($key);

            if (empty($userInfo)) {
                return Common::fail(Error::PLEASE_LOGIN_FIRST, Error::NOT_LOGGED_CODE);
            }

            $expire = config('redis_key.api.user_login_expire');
            $expireTime = time() + $expire;

            $userData = json_decode($userInfo, true);
            // 判断ip 切换网络有问题
            // if (isset($userData['ip']) && $userData['ip'] != Common::getClientIp()) {
            //     return Common::fail(Error::PLEASE_LOGIN_FIRST, Error::NOT_LOGGED_CODE);
            // }
            $userData['expire_time'] = $expireTime;
            $userData['token'] = $token;

            $redis->set($token, $uid, $expire);
            $redis->set($key, json_encode($userData), $expire);
        }
        return $next($request);
    }


}